package com.leishixiong.blog.service;

import com.leishixiong.blog.model.User;
import com.leishixiong.dao.UserDao;
import org.mindrot.jbcrypt.BCrypt;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 雷世雄爸爸
 * Date: 2022-03-20
 * Time: 16:09
 */
public class UserService {
    private final UserDao userDao = new UserDao();

    public User register(String username, String nickname, String password, String avatar, String git) {
        // 1.1 将密码做 hash 后，再去保存
        String salt = BCrypt.gensalt();
        String hashpw = BCrypt.hashpw(password, salt);

        // 2. 将信息保存到数据库中
        return userDao.insert(username, nickname, hashpw, avatar, git);
    }

    public User login(String username, String password) {
        // 1. 获取登录用户信息
        User user = userDao.selectOneByUsername(username);

        // 2. 验证密码是否正确
        if (user == null) {
            return null;
        }

        if (BCrypt.checkpw(password, user.password)) {
            return user;
        }

        return null;
    }
}
